using System;
using System.Configuration;
using System.IO;
using System.Reflection;

namespace AntEater.ComponentModel.Configuration
{
    /// <summary>
    /// Provides Access the the configuration.
    /// </summary>
    public class AntEaterConfiguration : ConfigurationSection
    {
        // Name of the AntEater section
        private const string ANTEATERCONFIGFILE = "AntEater.config";
        private const string ANTEATERSECTIONNAME = "antEater";

        /// <summary>
        /// Initializes a new instance of the <see cref="AntEaterConfiguration"/> class.
        /// </summary>
        public AntEaterConfiguration() {

            // Get the path of the config file            
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), AntEaterConfiguration.ANTEATERCONFIGFILE);

            // Open the configuration file and read the the AntEater section
            System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            _antEater = new AntEaterSection();

            // Parse AppSettings Section of config file
            foreach (KeyValueConfigurationElement element in config.AppSettings.Settings) {
                // Get values from elements
                string key = element.Key;
                string[] values = element.Value.Split(new string[] { ";" }, StringSplitOptions.None);

                if (values.Length == 3) {
                    switch (values[0]) {
                        case "RuntimeService":
                            // Add new runtime service
                            _antEater.RuntimeServices.Add(new RuntimeServiceElement(key, values[1], values[2]));
                            break;

                        case "Presenter":
                            // Add new presenter
                            _antEater.Presenters.Add(new PresenterElement(key, values[1], values[2]));
                            break;
                    }
                }
            }
        }

        private AntEaterSection _antEater;

        /// <summary>
        /// Gets or sets the ant eater section.
        /// </summary>
        /// <value>The ant eater section.</value>
        public AntEaterSection AntEater {
            get { return _antEater; }
        }
    }
}
